package weaver.ihg.servlet;

import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.core.context.Context;
import com.engine.workflow.biz.requestList.RequestListBiz;
import com.engine.workflow.cmd.publicApi.reqOperate.DoIntervenorCmd;
import com.engine.workflow.constant.PAResponseCode;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.service.impl.RequestFormServiceImpl;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.util.JSONUtil;
import weaver.workflow.workflow.WorkflowAllComInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/changeOpertorMethod")
public class WebUtilsServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doGet(req, res);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doPost(req, res);
    }

    private RequestFormServiceImpl getFormService(User user) {
//        User user = RequestFormBiz.getFormUser(request, response, false);
//        User user=new User(1);
        return (RequestFormServiceImpl) ServiceUtil.getService(RequestFormServiceImpl.class, user);
    }

    private String getWorkflowid(String requestid) {
        String workflowid = "";

        RecordSet rs = new RecordSet();
        rs.executeQuery(" select  workflowid from workflow_requestbase  where requestid = " + requestid);
        if (rs.next()) {
            workflowid = rs.getString("workflowid");
        }
        return workflowid;
    }

    private String getTablename(String workflowid) {
        String tablename = "";
        try {
            WorkflowAllComInfo workflowAllComInfo = new WorkflowAllComInfo();
            int formid = com.weaver.general.Util.getIntValue(workflowAllComInfo.getFormId(workflowid), 0);
            int isbill = com.weaver.general.Util.getIntValue(workflowAllComInfo.getIsBill(workflowid));
            if (formid == 0) {
                String sql = "select formid,isbill from workflow_base where id = " + workflowid;
                RecordSet rs = new RecordSet();
                rs.execute(sql);
                if (rs.next()) {
                    formid = rs.getInt("formid");
                    isbill = rs.getInt("isbill");
                }
            }
            tablename = getTablename(formid, isbill);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tablename;
    }

    /**
     * 获取流程主表名称
     *
     * @param formid
     * @param isbill
     * @return
     */
    private String getTablename(int formid, int isbill) {
        RecordSet rs = new RecordSet();
        String billtablename = "";
        if (isbill == 1) {
            rs.executeQuery("select tablename from workflow_bill where id =? ", formid); // 查询工作流单据表的信息
            if (rs.next())
                billtablename = rs.getString("tablename");          // 获得单据的主表
        } else {
            billtablename = "workflow_form";
        }
        return billtablename;
    }

    //http://localhost:8082/changeOpertorMethod?requestId=525528&workflowid=44&nodeid=177&field5=27&forwardflag=3&isShowReplyNotice=0&agentType=0&agentorByAgentId=-1&isRemind=0&isChuanyue=0&isSubmitSign=0
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        BaseBean baseBean = new BaseBean();
        Map para2Map = ParamUtil.request2Map(request);
        baseBean.writeLog("para2Map====>" + JSONUtil.toJSONString(para2Map));
        String requestid = (String) para2Map.get("requestid");//当前请求id值
        String operateUserId = (String) para2Map.get("operateUser");//当前当前操作用户id
        User user = new User(Integer.valueOf(operateUserId));
        baseBean.writeLog("user====>" + user.getLoginid());
        RecordSet recordSet = new RecordSet();
        String nodeid = (String) para2Map.get("nodeid");//当前节点id
        String workflowid = (String) para2Map.get("workflowid");//workflowid
        String newNodeId = (String) para2Map.get("newNodeId");//workflowid
        baseBean.writeLog("newNodeId====>" + newNodeId);
        String tablename = getTablename(workflowid);
        baseBean.writeLog("tableName===>" + tablename);
        String sql2 = "update " + tablename + " set hdcjr=? where requestid='" + requestid + "'";
        int field5 = Util.getIntValue(request.getParameter("field5"));//新的人
        recordSet.executeUpdate(sql2, field5);
        baseBean.writeLog("sql2===>" + sql2);
        int forwardflag = Util.getIntValue(request.getParameter("forwardflag"));//转办
        String operate = Util.null2String(request.getParameter("operate"), "save");//操作类型，保存日志
        baseBean.writeLog("reququestId==>" + requestid + "====nodeid===>" + nodeid + "===>field5==>" + field5 + "===>operate==>" + operate + "===>workflowid===>" + workflowid);
        //找到流程基础信息表的创建人，对应的操作节点信息的人，修改成新的人
        String sql = "select CREATER from workflow_requestbase where requestid='" + requestid + "'";
        baseBean.writeLog("sql===>" + sql);
        recordSet.execute(sql);
        Map<String, Object> apidatas = getFormService(user).forwardSubmit(request);
//        Map<String, Object> apidatas = getFormService(request, response).forwardSubmit(request);
        String openByDefaultBrowser = "".equals(Util.null2String(request.getParameter("openByDefaultBrowser"))) ? "1" : "0";
        baseBean.writeLog("openByDefaultBrowser====>" + openByDefaultBrowser);


        /*
        流程干预，更改流程节点信息
         */
        // user         干预操作者
        // requestId    请求ID
        // submitNodeId 目标节点ID
        // enable       是否执行节点前附加操作
        // signType     会签类型 0 ：非会签 1：会签 2：依次逐个处理
        // receiveIds   干预节点接收人，多个人以","号隔开
        // remark       操作意见
        if (nodeid != null && !newNodeId.equals(nodeid)) {
            baseBean.writeLog("node change start");
            String remark = "任务变更执行操作";
            boolean enable = true;
            int signType = 1;
            int submitNodeId = Integer.valueOf(newNodeId);
            String receiveIds = String.valueOf(field5);
            ReqOperateRequestEntity param1 = new ReqOperateRequestEntity();
            param1.setRequestId(Integer.valueOf(requestid));
            param1.setRemark(remark);
            param1.setEnableIntervenor(enable);
            param1.setSignType(signType);
            param1.setSubmitNodeId(submitNodeId);
            param1.setIntervenorid(receiveIds);
            DoIntervenorCmd doIntervenorCmd = new DoIntervenorCmd(user, param1);
            PAResponseEntity execute = doIntervenorCmd.execute(Context.getCommandComtext());
            PAResponseCode code = execute.getCode();
            baseBean.writeLog("doIntervenor code====>" + code);
        }


        if (forwardflag == 3 && "1".equals(openByDefaultBrowser)) {
            RequestListBiz.putRecord(user, requestid);
        }

        if (recordSet.next()) {
            String creater = recordSet.getString("CREATER");
            baseBean.writeLog("creater===>" + creater);
            //更新节点操作者记录表的当前节点的人为新的人
            String updateSql = "\n" +
                    "update workflow_currentoperator  set userId=" + field5 + "\n" +
                    " where requestid=" + requestid + " and userId=" + creater + "";
            baseBean.writeLog("updateSql==>" + updateSql);
            recordSet.execute(updateSql);

//            String updateSql2="\n" +
//                    "update workflow_currentoperator  set userId="+field5+"\n" +
//                    " where requestid="+requestId+" and nodeid='"+nodeid+"'";
//            baseBean.writeLog("updateSql2==>"+updateSql2);
//            recordSet.execute(updateSql2);
            //更新流程表基本信息的创建者为新的人
            String updateBaseCreateToNewSql = "update workflow_requestbase  set creater=" + field5 + "\n" +
                    " where requestid='" + requestid + "'";
            baseBean.writeLog("updateBaseCreateToNewSql====>" + updateBaseCreateToNewSql);
            recordSet.execute(updateBaseCreateToNewSql);
        }

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(JSONUtil.toJSONString(apidatas));
    }
}
